<?php

namespace app\controller\warehouse;

use app\Auth;
use app\BaseController;
use app\models\warehouse\Order as orderModel;
use lc\helpers\Response;
use think\facade\Db;

class Order extends BaseController
{

    /**
     * 获取商品以及分类
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOneCategory()
    {
        $data = Db::table('xd_store_category')->where(['pid' => 0, 'is_show' => 1])->order('sort desc,id desc')->select()->toArray();;
        return response::success($data);
    }


    /**
     * 获取商品列表
     * @return void
     */
    public function getProductData(){

        $adminId = Auth::$adminId;

        $search = $_REQUEST['search'] ?? '';
        $size = $_REQUEST['size'] ?? '15';
        $cateId = $_REQUEST['cateId'] ?? '';

        $query = Db::table('xd_store_product')
            ->where('is_show',1)
            ->where('is_del',0)
            ->whereIn('product_type',[0,2])
            ->whereLike('store_name','%'.$search.'%');

        if(!empty($cateId)){
            $query = $query->where('cate_id',$cateId);
        }
           $productData = $query->order('sort desc,sales desc,id desc')
            ->paginate($size);

        return response::success($productData);
    }


    /**
     * 获取游客编号
     * @return void
     */
    public function getTouristUid(){

        $adminId = Auth::$adminId;
        $touristUid = time().$adminId.rand(10000,99999);
        return response::success($touristUid);
    }


    /**
     * 添加购物车
     */

    public function setCart(){

        $adminId = Auth::$adminId;
        $uId = $_REQUEST['uid'];
        $productId = $_REQUEST['productId'];
        $touristUid = $_REQUEST['touristUid'];
        $cartNum = $_REQUEST['cartNum'];

        //查询商品属性
        $productAttr = Db::table('xd_store_product_attr_value')->field('unique')->where('product_id',$productId)->find();

        //入购物车库
        $cartId = Db::table('xd_store_cart')->insertGetId([
            'uid'=>empty($uId) ?? 0,
            'tourist_uid'=>empty($touristUid) ?? '',
            'product_id'=>$productId,
            'store_id'=>$adminId,
            'product_attr_unique'=>$productAttr['unique'],
            'cart_num'=>$cartNum,
            'add_time'=>time(),
        ]);

        return response::success([
            'cart_id'=>$cartId
        ]);
    }




    /**
     * 购物车商品修改数量
     */
    public function setCartNum(){

        $adminId = Auth::$adminId;
        $cartId = $_REQUEST['cateId'];
        $productId = $_REQUEST['productId'];
        $type = $_REQUEST['type'];

        if($type == 1){
            //增加
            $data = Db::table('xd_store_cart')->where('id',$cartId)->where('product_id',$productId)->inc('cart_num');
        }else{
            //减少
            $data = Db::table('xd_store_cart')->where('id',$cartId)->where('product_id',$productId)->dec('cart_num');
        }

        if($data != 0){
            return response::success();
        }else{
            return response::fail('修改数量失败');
        }
    }


    /**
     * 购物车删除商品or清空
     */

    public function removeCart(){

        $uId = $_REQUEST['uId'];
        $touristUid = $_REQUEST['touristUid'];
        $cartId = $_REQUEST['cartId'];

        if(empty($productId)){
            //清空购物车
            if(empty($uId)){
                Db::table('xd_store_cart')->where('uid',$uId)->delete();
            }elseif(empty($touristUid)){
                Db::table('xd_store_cart')->where('tourist_uid',$touristUid)->delete();
            }else{
                return response::fail('网络错误,请刷新重试');
            }
        }else{
            Db::table('xd_store_cart')->where('id',$cartId)->delete();
        }

        return response::success();
    }

    /**
     * 用户选择数据
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function userData(){

        $adminId = Auth::$adminId;

        $search = $_REQUEST['search'] ?? '';
        $size = $_REQUEST['size'] ?? '15';

        $userData = Db::table('xd_user')
            ->field('uid,real_name,phone,now_money,pay_count')
            ->where('status',1)
            ->where('is_del',0)
            ->whereLike('phone','%'.$search.'%')
            ->where('phone','>',1)
            ->order('uid','desc')
            ->paginate($size);

        return response::success($userData);
    }


    /**
     * 计算购物车金额
     * @return void
     */
    public function cartPrice(){

        $adminId = Auth::$adminId;
        $uId= $_REQUEST['uId'] ?? '';
        $touristUid = $_REQUEST['touristUid'] ?? '';

        $orderModel = new orderModel();

        $res = $orderModel->getCartData($uId,$touristUid);

        return response::success($res);

    }


    /**
     * 创建订单
     * @return void
     */

    public function createOrder(){
        //
        $adminId = Auth::$adminId;
        $uId= $_REQUEST['uId'] ?? '';
        $touristUid = $_REQUEST['touristUid'] ?? '';
        $cartId = $_REQUEST['cartId'] ?? [];

        $orderModel = new orderModel();

        //生成订单id
        $orderId = $orderModel->getNewOrderId($uId ?? $touristUid);

        //获取商品总数量
        $res = $orderModel->getCartData($cartId);

        //新增订单
        $data = array(
            "order_id"=>$orderId,
            'uid'=>$uId ?? 0,
            'real_name'=>'',
            'user_phone'=>'',
            'user_address'=>'',
            'cart_id'=>json_encode($cartId),
            'total_num'=>$res['num'],
            'total_price'=>$res['price'],
            'total_postage'=>0,
            'pay_price'=>$res['price'],
            'pay_type'=>'Q_cash',
            'poi_id'=>'',
            'add_time'=>time(),
            'dy_order_id'=>'',
            'item_order_id'=>'',
            'unique'=>md5($orderId),
            'promotions_give'=>'{"give_integral":0,"give_coupon":[],"give_product":[],"promotions":[]}',
            'admin_id'=>$adminId,
            'paid'=>1,
            'pay_time'=>time()
        );

        $orderGetId = Db::table('xd_store_order')->insertGetId($data);

        //添加购物车信息
        //获取商品信息
        $cartData = Db::table('xd_store_cart')->field('id,product_id')->whereIn('id',$cartId)->select();

        if(empty($cartData)){
            return response::fail('参数错误,请刷新重试');
        }

        foreach($cartData as $k => $v){

            $cartRes = Db::table('xd_store_cart')->field('product_id')->where('id',$v['id'])->find();

            $good = $orderModel->getgoodDeilt($cartRes['product_id']);


            $res = $orderModel->getCartData($v['product_id']);
            $price = $res['price'];

            $prdinfo = '{"id":"'.$v['product_id'].'","type":0,"store_id":0,"tourist_uid":"","product_type":0,"activity_id":0,"discount_product_id":0,"product_id":'.$v['product_id'].',"product_attr_unique":"'.$good['value']['unique'].'","cart_num":1,"productInfo":'.json_encode($good).',"attrInfo":'.json_encode($good['value']).',"sum_price":"'.$price.'","truePrice":'.$price.',"trueStock":1000,"costPrice":"0.00","is_gift":0,"attrStatus":true,"vip_truePrice":0,"price_type":"level","is_valid":1,"postage_price":0,"use_integral":0,"integral_price":0,"one_brokerage":"0.00","two_brokerage":"0","sum_true_price":"'.$price.'"}';

            $card = array(
                'uid'=>$uId ?? 0,
                'oid'=>$orderGetId,
                'cart_id'=>$v['id'],
                'product_id'=>$v['product_id'],
                'cart_num'=>$res['num'],
                'unique'=>md5($v['id']),
                'cart_info'=>$prdinfo,
                'add_time'=>time(),
            );

            Db::table('xd_store_order_cart_info')->insert($card);
        }

        return response::success();
    }


    /**
     * 订单列表
     * @return void
     */
    public function orderList(){

        $adminId = Auth::$adminId;
        $size = $_REQUEST['size'] ?? '15';

        $orderList = orderModel::with(['orderCartInfo'])
            ->where('admin_id',$adminId)
            ->paginate($size)->toArray();

        if(!empty($orderList['data'])){
            foreach($orderList['data'] as $a => $b){
                if(!empty($b['orderCartInfo'])){
                    foreach($b['orderCartInfo'] as $k => $v){
                        $orderList['data'][$a]['orderCartInfo'][$k]['cart_info'] = json_decode($v['cart_info']);
                    }
                }
            }
        }

        return response::success($orderList);
    }















}
